<script setup lang="ts">
  import { BasicTable, useTable, TableAction } from '@/components/Table';
  import { useDrawer } from '@/components/Drawer';
  import { columns, searchFormSchema } from './util/gateway.data';
  import {
    deleteRouterById,
    gatewayRouterDel,
    pageList,
    refreshAllGateway,
    refreshSignGateway,
  } from '@/api/system/gateway';
  import GatewayDrawer from './drawer/GatewayDrawer.vue';
  import { message } from 'ant-design-vue';

  defineOptions({ name: 'GatewayManagement' });
  const [registerDrawer, { openDrawer }] = useDrawer();
  const [registerTable, { reload }] = useTable({
    title: '网关列表',
    api: pageList,
    columns,
    formConfig: {
      labelWidth: 120,
      schemas: searchFormSchema,
    },
    useSearchForm: true,
    showTableSetting: true,
    bordered: true,
    showIndexColumn: false,
    actionColumn: {
      width: 80,
      title: '操作',
      dataIndex: 'action',
      // slots: { customRender: 'action' },
      fixed: undefined,
    },
  });
  function handleCreate() {
    openDrawer(true, {
      isUpdate: false,
    });
  }

  function handleEdit(record: Recordable) {
    openDrawer(true, {
      record,
      isUpdate: true,
    });
  }

  async function handleDelete(record: Recordable) {
    // 1. 先删除网关配置
    await gatewayRouterDel(record.id);
    // 2. 删除数据库数据
    await deleteRouterById(record.id);
    // 3. 刷新列表
    await reload();
  }

  function handleSuccess() {
    reload();
  }

  async function handleSyncSign(record: Recordable) {
    await refreshSignGateway(record);
    message.success('服务《' + record.serverName + '》同步成功');
  }

  async function handleSyncAll() {
    await refreshAllGateway();
    message.success('同步所有网关成功');
  }
</script>

<template>
  <div>
    <BasicTable @register="registerTable">
      <template #toolbar>
        <a-button type="primary" @click="handleCreate"> 新增网关 </a-button>
        <a-button type="primary" @click="handleSyncAll"> 同步所有网关 </a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                icon: 'ant-design:sync-outlined',
                onClick: handleSyncSign.bind(null, record),
                tooltip: '同步到网关服务',
              },
              {
                icon: 'clarity:note-edit-line',
                onClick: handleEdit.bind(null, record),
                tooltip: '编辑',
              },
              {
                icon: 'ant-design:delete-outlined',
                color: 'error',
                popConfirm: {
                  title: '是否确认删除',
                  placement: 'left',
                  confirm: handleDelete.bind(null, record),
                },
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <GatewayDrawer @register="registerDrawer" @success="handleSuccess" />
  </div>
</template>
